package com.baselibrary.utils;

import android.os.Handler;
import android.os.Message;

public class CountDown {

    private static final String TAG = "CountDown";
    private CountDownHandler mCountDown;
    private CountDownInterface downInterface;
    private int mCountDownWhat;
    public static final int COUNTDOWN_TIME = 9999;//获取验证码倒计时
    public static final int WELCOME_TIME = 8888;//欢迎页倒计时

    public CountDown(int countDownWhat, CountDownInterface downInterface,long delayMillis) {
        this.mCountDownWhat = countDownWhat;
        this.downInterface = downInterface;
        mCountDown = new CountDownHandler(countDownWhat, downInterface,delayMillis);
    }

    public void startCountDown(int time, long delayMillis) {
        if (mCountDown == null && downInterface != null) {
            downInterface.countDownError();
            return;
        }
        Message message = mCountDown.obtainMessage();
        message.what = mCountDownWhat;
        message.obj = time;
        mCountDown.sendMessageDelayed(message, delayMillis);
    }

    private static class CountDownHandler extends Handler {


        private int mCountDownWhat;
        private CountDownInterface mDownInterface;
         private long delayMillis;

        CountDownHandler(int countDownWhat, CountDownInterface downInterface, long delayMillis) {
            mDownInterface = downInterface;
            this.mCountDownWhat = countDownWhat;
            this.delayMillis = delayMillis;

        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == mCountDownWhat) {

                int value = (int) msg.obj;
                if (mDownInterface != null && value <= 0) {
                    mDownInterface.countDownOver();
                    removeMessages(mCountDownWhat);
                    return;
                }
                if (mDownInterface != null)
                    mDownInterface.countDownIng(value / 1000);
                msg = Message.obtain();//重新获取消息
                msg.what = mCountDownWhat;
                msg.obj = value - 1000;
                sendMessageDelayed(msg, delayMillis);
            }
        }
    }

    public void removeMessages() {
        if (mCountDown != null)
            mCountDown.removeMessages(mCountDownWhat);
        if (downInterface != null)
            downInterface.countDownError();
    }
}
